package com.hiep.connect.server.dao;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.google.appengine.api.datastore.QueryResultIterator;
import com.google.common.collect.Lists;
import com.hiep.connect.shared.MyUser;
import com.hiep.connect.shared.Posting;
import com.hiep.connect.shared.PostingThread;

public class MyUserTwigDao extends TwigDAO {

	public MyUserTwigDao() {
		super();
	}

	public void save(MyUser user) {
		datastore.storeOrUpdate(user);
	}

	public void update(MyUser user) {
		// List<MyUser> friends = user.getFriends();
		// for (MyUser f : friends) {
		// datastore.update(f);
		// }
		//
		// List<PostingThread> postingThreads = user.getPostingThreads();
		// for (Iterator iterator = postingThreads.iterator();
		// iterator.hasNext();) {
		// PostingThread postingThread = (PostingThread) iterator.next();
		//
		// List<Posting> replies = postingThread.getReplies();
		// for (Iterator iterator2 = replies.iterator(); iterator2.hasNext();) {
		// Posting posting = (Posting) iterator2.next();
		// datastore.update(posting);
		// }
		//
		// datastore.update(postingThread);
		// }
		// datastore.update(user);

		// TODO a hack for now
		datastore.storeOrUpdate(user);
	}

	public void delete(MyUser user) {
		datastore.delete(user);
	}

	public MyUser find(MyUser user) {

		QueryResultIterator<MyUser> find = datastore.find(MyUser.class);

		while (find.hasNext()) {
			MyUser next = find.next();
			if (next.getEmail().equalsIgnoreCase(user.getEmail())) {
				return next;
			}
		}

		return null;
	}

	public List<MyUser> getAll() {
		QueryResultIterator<MyUser> find = datastore.find(MyUser.class);
		ArrayList<MyUser> arrayList = Lists.newArrayList(find);
		return arrayList;
	}
}
